//
//  MQComposeView.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/27.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import pop

class MQComposeView: UIView {
    
    lazy var composeMenuBtns:[UIButton] = [UIButton]()
    var target:UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        frame.size = CGSizeMake(SCREENW, SCREENH)
        backgroundColor = UIColor.purpleColor()
        
        
        let imageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
        addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        
        //添加6个btn
        addChildBtn()

    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (index, btn) in composeMenuBtns.reverse().enumerate(){
            
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            animation.toValue = NSValue(CGPoint: CGPoint(x: btn.center.x, y: btn.center.y + SCREENH*0.5))
            animation.springBounciness = 10
            animation.springSpeed = 8
            animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            btn.pop_addAnimation(animation, forKey: nil)
        }
//        self.performSelector("removeFromSuperViewBtn", withObject: self, afterDelay: 0.4)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()){
                self.removeFromSuperview()
            }
    }
    
    //当composeView添加到window上时执行此方法
    override func didMoveToWindow() {
        for (index, btn) in composeMenuBtns.enumerate(){
            
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            animation.toValue = NSValue(CGPoint: CGPoint(x: btn.center.x, y: btn.center.y - SCREENH*0.5))
            animation.springBounciness = 10
            animation.springSpeed = 8
            animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            btn.pop_addAnimation(animation, forKey: nil)
        }
    }
    
    
    private func addChildBtn(){
        
        //读取compose.plist文件
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        let composeBtnMenuInfos = NSArray(contentsOfFile: path!)
        
        let childBtnW:CGFloat = 80
        let childBtnH:CGFloat = 110
        let btnMargin:CGFloat = (SCREENW - 3 * childBtnW) / 4
        
        for (i, value) in composeBtnMenuInfos!.enumerate() {
            
            let dict = value as! NSDictionary
            let icon = dict["icon"] as! String
            let title = dict["title"] as! String
            
            //第几行
            let row = i / 3
            //第几列
            let col = i % 3
            
            let btnX = CGFloat(col + 1) * btnMargin + CGFloat(col) * childBtnW
            let btnY = CGFloat(row) * (btnMargin + childBtnH) + SCREENH
            
            let btn = MQComposeMenuButton()
            btn.frame = CGRectMake(btnX, btnY, childBtnW, childBtnH)
            btn.setTitle(title, forState: UIControlState.Normal)
            btn.setImage(UIImage(named:icon), forState: UIControlState.Normal)
            btn.addTarget(self, action: "childBtnsCilck:", forControlEvents: UIControlEvents.TouchUpInside)
            
            addSubview(btn)
            composeMenuBtns.append(btn)
        }
        
    }
    @objc private func childBtnsCilck(btn:UIButton){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.composeMenuBtns {
                
                if value == btn {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
                value.alpha = 0.01
            }

        }) { (_ ) -> Void in
//            UIView.animateWithDuration(0.25, animations: { () -> Void in
//                for value in self.composeMenuBtns{
//                    value.transform = CGAffineTransformIdentity
//                    value.alpha = 1
//                }
//                }, completion: { (_) -> Void in
//                    
//            })
            
//            let type = NSStringFromClass(MQComposeViewController.self)
            
            if let result = NSClassFromString("SinaWeiBo.MQComposeViewController") as? UIViewController.Type{
                let instance = result.init()
                self.target?.presentViewController(UINavigationController(rootViewController: instance), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
            }
            
            
        }
    }
 
    //外部调用添加view
    func showView(target:UIViewController){
        self.target = target
      target.view.addSubview(self)
    }
}
